/**
 * 用于修改表单 JSON，比如请假类型需要请求接口
 */
import request from '@/utils/request';
import { groupBy } from 'lodash';
import { modifyProps } from '@/pages/Flow/Mine/Apply/utils';
import { getOptionData, renderDict } from '@/pages/Flow/Mine/ApplyPage/utils';
import { dictionaryList } from '@/services/dictionary';
import { getDepartmentTree } from '@/services/components/userform';
import { getPostListByCondition } from '@/services/flowMine/apply';
import clone from 'lodash/clone';
import FORM_TYPE_MAP from './consts';

const removeEmptyChild = data => {
    const remove = arr => {
        arr.forEach(item => {
            if (item.children) {
                if (item.children.length > 0) {
                    remove(item.children);
                } else if (item.children.length === 0) {
                    // eslint-disable-next-line no-param-reassign
                    delete item.children;
                }
            }
        });
    };

    remove(data);

    return data;
};

const COUNTRY_TYPE_MAP = {
    xiamen: 'China',
    shenzhen: 'China',
    singapore: 'Singapore'
};

const didMount = async ({
    formType,
    json,
    setJson,
    setPostId,
    setLeaveTypeList,
    curPost,
    setPostType,
    setReason1,
    currentUser,
    setPageLoading,
    country,
    setInstitutionType,
    setPostList,
    valueJson,
    applicationNo,
    setIsDataReady
}) => {
    setIsDataReady(false);

    let { fields } = json;
    const countryType = COUNTRY_TYPE_MAP[country] || 'Group';
    const { formValueJson } = valueJson;

    if (formType === FORM_TYPE_MAP.TYPE_LEAVE) {
        // 获取请假类型，并赋值给自定义请假类型下拉组件
        const result = await request('/api/work/v1/attendance/leavetype/web/typelist', {
            method: 'POST'
        });

        if (result.code === 10000) {
            setJson({
                ...json,
                fields: modifyProps(
                    'leaveType',
                    {
                        data: result.data || []
                    },
                    fields
                )
            });
            setLeaveTypeList(result.data || []);
            setPageLoading(false);
        }
    } else if (formType === FORM_TYPE_MAP.TYPE_OVER_TIME) {
        // 获取加班类型
        const result = await dictionaryList({
            code: 'overtimeSign'
        });

        if (result.code === 10000) {
            // 前端过滤掉工作日的加班日类型
            let resultData = result.data || [];
            if (COUNTRY_TYPE_MAP[country] === 'China') {
                resultData = resultData.filter(item => item.dictValue !== '1');
            }
            const options = getOptionData(resultData, {
                key: 'dictValue',
                label: 'dictName'
            });
            setJson({
                ...json,
                fields: modifyProps(
                    'overTimeType',
                    {
                        options
                    },
                    fields
                )
            });
            setPageLoading(false);
        }
    } else if (formType === FORM_TYPE_MAP.TYPE_RESIGN_IN) {
        // 获取补卡类型
        const result = await dictionaryList({
            code: 'cardType'
        });

        if (result.code === 10000) {
            setJson({
                ...json,
                fields: modifyProps(
                    'type',
                    {
                        options: (result.data || []).map(item => ({
                            label: item.dictName,
                            value: item.dictValue
                        }))
                    },
                    fields
                )
            });
            setPageLoading(false);
        }
    } else if (formType === FORM_TYPE_MAP.TYPE_ON_BUSINESS) {
        // 获取交通方式
        const result = await dictionaryList({
            code: 'transportWay'
        });

        if (result.code === 10000) {
            setJson({
                ...json,
                fields: modifyProps(
                    'transportWay',
                    {
                        options: getOptionData(result.data || [], {
                            key: 'dictValue',
                            label: 'dictName'
                        })
                    },
                    fields
                )
            });
            setPageLoading(false);
        }
    } else if (formType === FORM_TYPE_MAP.TYPE_ON_RECRUIT) {
        // 获取需求部门
        const result = await getDepartmentTree({
            companyId: currentUser.companyId,
            permissionUrl: ''
        });
        if (result.code === 10000) {
            fields = modifyProps(
                'demandDepartmentId',
                {
                    options: removeEmptyChild(result.data),
                    fieldNames: {
                        label: 'departmentName',
                        value: 'id'
                    }
                },
                fields
            );
        }
        if (applicationNo && formValueJson.demandDepartmentId) {
            // 需求职位
            const recruitPostResult = await getPostListByCondition({
                departmentId: (formValueJson.demandDepartmentId && clone(formValueJson.demandDepartmentId).pop()) || ''
            });
            if (recruitPostResult.code === 10000) {
                setPostList(recruitPostResult.data);
            }
        }
        if (applicationNo === undefined) {
            // 需求职位
            const recruitPostResult = await getPostListByCondition({
                departmentId: ''
            });
            if (recruitPostResult.code === 10000) {
                setPostList(recruitPostResult.data);
            }
        }

        // 获取字典数据，如：汇报对象，类型，职级
        const codes = [
            COUNTRY_TYPE_MAP[country] === 'China' ? 'ChinaRecruitPostType' : 'SingaporeRecruitPostType',
            COUNTRY_TYPE_MAP[country] === 'China' ? 'jobNature' : 'jobType',
            `${countryType}Post`,
            COUNTRY_TYPE_MAP[country] === 'China' ? 'supplyReasonLevel' : 'SingaporeSupplyReasonLevel',
            'candidateSexType',
            'agreeType',
            'necessaryLevel',
            'timeEmployedType',
            'languageAbility'
        ];

        const resultDicts = await dictionaryList({
            codes
        });

        if (resultDicts.code === 10000) {
            const group = groupBy(resultDicts.data, 'code');
            console.log(group, 'group');
            fields = renderDict(
                fields,
                'postType',
                group[COUNTRY_TYPE_MAP[country] === 'China' ? 'ChinaRecruitPostType' : 'SingaporeRecruitPostType'],
                false,
                setPostType
            );
            fields = renderDict(
                fields,
                'workNature',
                group[COUNTRY_TYPE_MAP[country] === 'China' || country === 'shenzhen' ? 'jobNature' : 'jobType'],
                true
            );
            fields = renderDict(fields, 'recruitPost', group[`${countryType}Post`]);
            fields = renderDict(fields, 'recruitReport', group[`${countryType}Post`]);
            fields = renderDict(
                fields,
                'reason1',
                group[COUNTRY_TYPE_MAP[country] === 'China' ? 'supplyReasonLevel' : 'SingaporeSupplyReasonLevel'],
                false,
                setReason1
            );
            fields = renderDict(fields, 'requireSex', group.candidateSexType, true);
            fields = renderDict(fields, 'requireDegree', group.agreeType);
            fields = renderDict(fields, 'necessary', group.necessaryLevel);
            fields = renderDict(fields, 'timeEmployed', group.timeEmployedType);
            fields = renderDict(fields, 'languageAbility', group.languageAbility, true);
        }
        fields = modifyProps(
            'recruitPost',
            {
                allowClear: true,
                showSearch: false,
                showArrow: true,
                placeholder: ''
            },
            fields
        );
        setJson({
            ...json,
            fields
        });
        setPageLoading(false);
    } else if (formType === FORM_TYPE_MAP.TYPE_ON_OFFER) {
        setPostId(formValueJson.entryPost);
        // 获取录用部门
        const result = await getDepartmentTree({
            companyId: currentUser.companyId,
            permissionUrl: ''
        });
        if (result.code === 10000) {
            fields = modifyProps(
                'demandDepartmentId',
                {
                    options: removeEmptyChild(result.data),
                    fieldNames: {
                        label: 'departmentName',
                        value: 'id'
                    }
                },
                fields
            );
        }

        // 获取字典数据，如试用期长度、离职通知期
        let codes = [
            'sexType',
            'agreeType',
            `${countryType}OfferPostType`,
            `${countryType}Post`,
            'asian',
            'tryDuration'
        ];
        if (COUNTRY_TYPE_MAP[country] !== 'China') {
            codes = [
                ...codes,
                'AWSType',
                'accumulationFundType',
                'probationQuitNoticeType',
                'regularQuitNoticeType',
                'candidateRelationshipType'
            ];
        }

        const resultDicts = await dictionaryList({
            codes
        });

        if (resultDicts.code === 10000) {
            const group = groupBy(resultDicts.data, 'code');
            fields = renderDict(fields, 'talentSex', group.sexType, true);
            fields = renderDict(fields, 'talentAgree', group.agreeType, false);
            fields = renderDict(fields, 'tryDuration', group.tryDuration, false);
            fields = modifyProps(
                'nationalArea',
                {
                    asianData: group.asian,
                    fieldNames: {
                        label: 'dictName',
                        value: 'dictValue'
                    }
                },
                fields
            );
            fields = renderDict(fields, 'postType', group[`${countryType}OfferPostType`], false, setPostType);
            if (COUNTRY_TYPE_MAP[country] !== 'China') {
                fields = renderDict(fields, 'aws', group.AWSType, true);
                fields = renderDict(fields, 'accumulationFund', group.accumulationFundType, true);
                fields = renderDict(fields, 'probationQuitNotice', group.probationQuitNoticeType);
                fields = renderDict(fields, 'regularQuitNotice', group.regularQuitNoticeType);
                fields = renderDict(fields, 'firstBackRelationship', group.candidateRelationshipType);
                fields = renderDict(fields, 'secondBackRelationship', group.candidateRelationshipType);
            }
            if (curPost) {
                const postArr = await request('/api/oa/v1/post/getpostlistbycondition', {
                    method: 'POST',
                    data: {
                        departmentId: ''
                    }
                });

                if (postArr.code === 10000) {
                    const options = postArr.data.map(item => ({ ...item, id: String(item.id) }));
                    setPostList(options);
                }
            }
        }
        setJson({
            ...json,
            fields
        });
        setPageLoading(false);
    } else if (formType === FORM_TYPE_MAP.TYPE_GO_OUT) {
        setPageLoading(false);
    } else if (formType === FORM_TYPE_MAP.TYPE_ON_NEWS) {
        const newsType = await dictionaryList({
            code: 'newsType'
        });
        if (newsType.code === 10000) {
            fields = renderDict(fields, 'newsType', newsType.data, false);
        }
        setJson({
            ...json,
            fields
        });
        setPageLoading(false);
    } else if (formType === FORM_TYPE_MAP.TYPE_ON_SYSTEM) {
        const codes = [
            'institutionLevel', // 重要等级
            'institutionType', // 制度类型
            'institutionReleaseType', // 发布类型
            'auditEffectFlag' // 生效日期
        ];
        // 字典请求
        const resultDicts = await dictionaryList({
            codes
        });
        if (resultDicts.code === 10000) {
            const group = groupBy(resultDicts.data, 'code');
            fields = renderDict(fields, 'institutionLevel', group.institutionLevel, false);
            fields = renderDict(fields, 'institutionType', group.institutionType, false, setInstitutionType); // 制度类型联动 发布类型中已有制度修改更新的下拉数据
            fields = renderDict(fields, 'releaseType', group.institutionReleaseType, true);
            fields = renderDict(fields, 'auditEffectFlag', group.auditEffectFlag, true);
        }

        setJson({
            ...json,
            fields
        });

        console.log('loading....');
        setPageLoading(false);
    } else if (formType === FORM_TYPE_MAP.EDIT_SALARY) {
        setJson({
            ...json,
            fields: modifyProps(
                'version',
                {
                    type: formValueJson.ftype
                },
                fields
            )
        });
    }
    setIsDataReady(true);
};

export default didMount;
